package tpase.GlobalServer.DAO;

import tpase.GlobalServer.DO.PublicParam;
import tpase.GlobalServer.DO.PublicParameter;
import tpase.util.JDBCUtil;

import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PublicParameterDao {
    public void clearPublicParameter() {
        Connection connection = JDBCUtil.getConnect();
        String sql = "DELETE FROM public_parameter";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareCall(sql);
            statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, statement);
        }
    }

    public void storePublicParameter(PublicParameter publicParameter) {
        Connection connection = JDBCUtil.getConnect();
        String sql = "INSERT INTO public_parameter (t, n) VALUES (?, ?)";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareCall(sql);
            statement.setInt(1, publicParameter.getT());
            statement.setInt(2, publicParameter.getN());
            statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, statement);
        }
    }

    public PublicParameter getPublicParameter() {
        Connection connection = JDBCUtil.getConnect();
        String sql = "SELECT t, n FROM public_parameter";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        PublicParameter publicParameter = null;
        try {
            statement = connection.prepareCall(sql);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                int t = resultSet.getInt("t");
                int n = resultSet.getInt("n");
                publicParameter = new PublicParameter(t, n);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, statement, resultSet);
        }
        if (publicParameter == null) {
            throw new RuntimeException("getPublicParameter, 获取t 和 n 为空");
        }
        return publicParameter;
    }

    public static void main(String[] args) {
        PublicParameterDao publicParameterDao = new PublicParameterDao();
        publicParameterDao.clearPublicParameter();
        publicParameterDao.storePublicParameter(new PublicParameter(2, 3));
        PublicParameter publicParameter2 = publicParameterDao.getPublicParameter();
        System.out.println(publicParameter2.getT() + ", " + publicParameter2.getN());
    }
}
